<template>
  <el-dialog drag v-model="show" width="450px" title="文件下载" center draggable append-to-body>
    <el-progress :percentage="100" :indeterminate="true" :showText="false" />
    <p style="padding-top: 10px; text-align: center">文件正在下载，请稍等</p>
  </el-dialog>
</template>
<script setup>
import { ref, getCurrentInstance } from 'vue'
import { useAuthStore } from '@/stores/user'
const { token } = useAuthStore().user
let show = ref(false)
import axios from 'axios'
import Qs from 'qs'

let title

function open(downUrl, params, fileName) {
  let dt = new Date()
  let ymd = [
    dt.getFullYear(),
    (dt.getMonth() + 1).toString().padStart(2, '0'),
    dt.getDay().toString().padStart(2, '0')
  ]
  let hms = [
    dt.getHours().toString().padStart(2, '0'),
    dt.getMinutes().toString().padStart(2, '0'),
    dt.getSeconds().toString().padStart(2, '0')
  ]
  let ts = [ymd.join(''), hms.join('')].join('_')

  show.value = true
  var instance = axios.create({
    timeout: 1000 * 90,
    baseURL: '/api',
    headers: {
      Accept: 'application/json',
      'Content-Type': 'application/x-www-form-urlencoded',
      Authorization: token
    }
  })

  instance({
    url: downUrl,
    method: 'post',
    responseType: 'blob',
    data: Qs.stringify(params)
  }).then((res) => {
    if (res.status != 200) {
      show.value = false
      ElMessage({ type: 'error', message: '下载失败，请重试' })
    }
    let blob = new Blob([res.data], {
      type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'
    })
    if (window.navigator && window.navigator.meSaveOrOpenBlob) {
      window.navigator.meSaveOrOpenBlob(blob, fileName + '_' + ts + '.xlsx')
    } else {
      let blobUrl = window.URL.createObjectURL(blob)
      let link = document.createElement('a')
      link.style.display = 'none'
      link.href = blobUrl
      link.setAttribute('download', fileName + '_' + ts + '.xlsx')
      document.body.appendChild(link)
      link.click()
      ElMessage({ type: 'success', message: '下载完成' })
      show.value = false
    }
  })
}

defineExpose({ open })
</script>
